package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import xyz.hubery.domain.User;
import xyz.hubery.domain.UserBank;
import xyz.hubery.mapper.UserBankMapper;
import xyz.hubery.service.UserBankService;
import xyz.hubery.service.UserService;
import xyz.hubery.vo.BindBankRequest;

@Service
public class UserBankServiceImpl extends ServiceImpl<UserBankMapper, UserBank> implements UserBankService {


    @Autowired
    private UserService userService;


    @Override
    public UserBank geyByUserId(Long userId) {
        return getOne(new LambdaQueryWrapper<UserBank>().eq(UserBank::getUserId, userId).eq(UserBank::getStatus, 1));
    }

    @Transactional
    @Override
    public boolean addUserBank(Long userId, BindBankRequest bankRequest) {
        // 查询用户
        User user = userService.getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 设置支付密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPaypassSetting(true);
        user.setPaypassword(passwordEncoder.encode(bankRequest.getPayPassword()));
        // 更新用户信息
        userService.updateById(user);

        // 新增银行卡信息(先根据用户id查询，存在银行卡则进行更新操作
        UserBank userBank = geyByUserId(userId);
        if(userBank != null) {
            userBank.setBank(bankRequest.getBank());
            userBank.setBankCard(bankRequest.getBankCard());
            userBank.setRealName(bankRequest.getRealName());
            userBank.setRemark(bankRequest.getRemark());
            userBank.setStatus((byte)1);
            return updateById(userBank);
        }

        userBank = new UserBank();
        userBank.setUserId(userId);
        userBank.setBank(bankRequest.getBank());
        userBank.setBankCard(bankRequest.getBankCard());
        userBank.setRealName(bankRequest.getRealName());
        userBank.setRemark(bankRequest.getRemark());
        userBank.setStatus((byte)1);
        return this.save(userBank);
    }
}
